import random
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
import os
np.random.seed(1337)
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dropout, Dense, Activation, Convolution2D, MaxPooling2D, Flatten
from keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from PIL import Image
from keras.callbacks import ModelCheckpoint
from matplotlib import pyplot as plt

# 数据集
def read_image(img_name):
    im = Image.open(img_name).convert('L')
    data = np.array(im)
    return data
images = []
imagespath=r'F:\underwater robots\神经网络\train\mypic'
labelpath=r'F:\underwater robots\神经网络\train\newtest.txt'

for fn in os.listdir(imagespath):
    if fn.endswith('.jpg'):
        fd = os.path.join(imagespath,fn)
        images.append(read_image(fd))
print('load success!')
X = np.array(images)
y = np.loadtxt(labelpath)


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state= 30)

num_pixels = X_train.shape[1] * X_train.shape[2]

X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
# 格式化数据到0-1之前
X_test = X_test / 255
# one-hot编码
y_test = np_utils.to_categorical(y_test)

print("X_test.shape:",X_test.shape,"y_test.shape:",y_test.shape)

index = random.randint(0, X_test.shape[0])
x = X_test[index,:].reshape((1,784))
y = y_test[index]
print("x.shape:",x.shape,"y.shape:",y.shape)

# 加载
mymodel = load_model('total.h5')

# 预测

predict = mymodel.predict(x)
predict = np.argmax(predict)#取最大值的位置

print('index:', index)
print('original:', y)
print('predicted:', predict)
mymodel.summary()